package zpengblog.taskdemo.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import zpengblog.taskdemo.aop.custom.TaskRedisLock;
import zpengblog.taskdemo.util.RedisLockUtils;

import java.time.LocalDateTime;

/**
 * @author linzp
 * @version 1.0.0
 * CreateDate 2021/1/14 11:58
 */
@Component
@Slf4j
public class TaskDemo {

    @Value("${name}")
    private String name;

    @Autowired
    private RedisLockUtils redisLockUtils;

    @Scheduled(cron = "0/5 * * * * *")
    public void start(){
        try {
            Boolean lock = redisLockUtils.getLock("test", 2000);
            //获取锁
            if (lock) {
                log.info("机器【2】上的 demo 定时任务启动了！>> 当前时间 [{}]", LocalDateTime.now());
                //延迟一秒
                Thread.sleep(1000);
            }else {
                log.error("获取锁失败了，此次不执行！");
            }
        }catch (Exception e){
            log.info("获取锁异常了！");
        }finally {
            //释放redis锁
            redisLockUtils.delLock("test");
        }
    }

    /**
     * 通过aop来加锁.
     */
    @TaskRedisLock(taskName = "task_1", expireTime = 4000)
//    @Scheduled(cron = "0/5 * * * * *")
    public void run(){
        log.info("task_1 定时任务启动了！>> 当前时间 [{}]", LocalDateTime.now());
        try {
            //延迟一秒
            Thread.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

//    @Scheduled(cron = "0/5 * * * * *")
    public void runTask(){
        log.info("机器【1】上的 demo 定时任务启动了！>> 当前时间 [{}]", LocalDateTime.now());
        try {
            //延迟，模拟业务逻辑
            Thread.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
